import time
import pywebio
from pywebio import start_server
from pywebio.input import *
from pywebio.output import *
from logic.convert_run import Work

from logic.tools import calculate_sha

import os

import time
import threading

def refresh():
    put_html(
        '''<button style="padding: 10px 20px; background-color: #4CAF50; color: white; border: none; border-radius: 5px; box-shadow: 2px 2px 5px rgba(0,0,0,0.3);" onclick="window.location.reload();">处理新的文件</button>
   ''' )

def display_md():
    with open('WEB_SHOW.md', 'r',encoding='utf-8') as md:
        md = md.read()
        put_markdown(md)


def display_files(files):
    put_text('您添加了以下文件：')
    for file in files:
        put_text(file['filename'])


def save_files_locally(files):
    local_files = []
    for file in files:
        user_file_path = 'user_upload_files/' + file['filename']
        with open(user_file_path, 'wb') as f:
            f.write(file['content'])
        local_files.append(user_file_path)
    return local_files


def process_files(local_files):
    threads = []
    for file_path in local_files:
        save_file_name = "processed_files/" + os.path.basename(file_path) + "." + calculate_sha(file_path)[
                                                                                  :10] + ".xlsx"
        thread = Work(file_path=file_path, save_file_name=save_file_name)
        thread.start()
        threads.append(thread)
    return threads


def wait_for_threads(threads):
    while not all(thread.is_finished() for thread in threads):
        put_text('正在处理，请稍等...')
        time.sleep(1)


def output_processed_files(local_files):
    put_text('任务处理完成！')
    for file_path in local_files:
        processed_file = "processed_files/" + os.path.basename(file_path) + "." + calculate_sha(file_path)[
                                                                                  :10] + ".xlsx"
        if os.path.exists(processed_file):
            with open(processed_file, 'rb') as f:
                put_file(os.path.basename(file_path), f.read())


def clean_folder(folder_path):
    for filename in os.listdir(folder_path):
        file_path = os.path.join(folder_path, filename)
        if os.path.isfile(file_path):
            os.remove(file_path)

def run_cleaning():
    folder_path = "processed_files"  # 替换为实际的文件夹路径
    clean_folder(folder_path)

    folder_path2 = "user_upload_files"  # 替换为实际的文件夹路径
    clean_folder(folder_path2)

    # 设置定时器，每15天运行一次
    interval = 15 * 24 * 60 * 60  # 半个月的秒数
    threading.Timer(interval, run_cleaning).start()


def main():
    '''Word转换工具'''
    pywebio.config(title='Word转换工具')
    with use_scope('main', clear=True):

        # 启动清理函数
        # run_cleaning()

        # 显示md
        display_md()

        # 上传文件
        files = file_upload('请选择要处理的文件', accept='.xls,.xlsx', multiple=True, placeholder='选择要处理的文件，格式为docx')

    with use_scope('main',clear=True):
        # 显示上传的文件
        display_files(files)

        # 将上传的文件保存到本地
        local_files = save_files_locally(files)

        # 为每个本地文件启动一个线程进行处理
        threads = process_files(local_files)

        # 等待所有线程完成
        wait_for_threads(threads)

        # 输出处理后的文件
        output_processed_files(local_files)

        # 返回主页
        refresh()


if __name__ == '__main__':
    start_server(main, port=8082,cdn=False)
